package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.ChatMessageMapper;
import cn.edu.lingnan.mapper.ChatSessionMapper;
import cn.edu.lingnan.user.pojos.ChatMessage;
import cn.edu.lingnan.user.pojos.ChatSession;
import cn.edu.lingnan.utils.DeepSeekChatUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Service
public class ChatService {

    private DeepSeekChatUtil chatUtil;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    /**
     * 初始化聊天服务
     */
    public void initializeChatService(Long sessionId, Long userId) {
        validateUserAccess(sessionId, userId);
        JSONArray historyMessages = loadHistoryMessagesFromDatabase(sessionId);
        this.chatUtil = new DeepSeekChatUtil(historyMessages);
    }


    /**
     * 为用户新建一个会话，并返回会话ID
     */
    public Long createChatSession(ChatSession chatSession) {
        // 调用 Mapper 方法插入会话
        chatSessionMapper.insertChatSession(chatSession);

        // 获取生成的主键
        return chatSession.getSessionId(); // 主键会自动填入
    }







    /**
     * 校验用户对会话的访问权限
     */
    private void validateUserAccess(Long sessionId, Long userId) {
        ChatSession session = chatSessionMapper.selectChatSessionById(sessionId);
        if (session == null || !userId.equals(session.getUserId())) {
            throw new SecurityException("Unauthorized access to session");
        }
    }

    /**
     * 从数据库加载会话的历史消息
     */
    private JSONArray loadHistoryMessagesFromDatabase(Long sessionId) {
        List<ChatMessage> messages = chatMessageMapper.selectChatMessagesBySessionId(sessionId);
        JSONArray result = new JSONArray();
        for (ChatMessage message : messages) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("role", message.getMessageRole());
            jsonObject.put("content", message.getMessageContent());
            result.add(jsonObject);
        }
        return result;
    }

    /**
     * 获取当前用户的所有会话
     */
    public JSONArray getAllSessionsByUserId(Long userId) {
        List<ChatSession> sessions = chatSessionMapper.selectChatSessionsByUserId(userId);
        JSONArray result = new JSONArray();
        for (ChatSession session : sessions) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sessionId", session.getSessionId());
            jsonObject.put("sessionTitle", session.getSessionTitle());
            jsonObject.put("createdAt", session.getCreatedAt());
            jsonObject.put("updatedAt", session.getUpdatedAt());
            result.add(jsonObject);
        }
        return result;
    }

    /**
     * 获取会话历史消息
     */
    public JSONArray getHistoryMessages(Long sessionId) {
        return loadHistoryMessagesFromDatabase(sessionId);
    }

    /**
     * 处理聊天请求，支持流式数据处理
     */
    @Transactional
    public void chat(Long sessionId, Long userId, String userInput, DeepSeekChatUtil.StreamingCallback callback) {
        validateUserAccess(sessionId, userId);
        chatUtil.addUserMessage(userInput);

        try {
            chatUtil.sendRequest(new DeepSeekChatUtil.StreamingCallback() {
                @Override
                public void onData(String data) {
                    callback.onData(data); // 处理流式数据
                }

                @Override
                public void onComplete() {
                    JSONArray newMessages = chatUtil.getNewHistoryMessages();
                    saveNewMessagesToDatabase(sessionId, newMessages); // 保存新的消息到数据库
                    callback.onComplete(); // 完成回调
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            callback.onComplete(); // 出现异常时，完成回调
        }
    }

    /**
     * 将新的消息保存到数据库
     */
    private void saveNewMessagesToDatabase(Long sessionId, JSONArray newMessages) {
        for (int i = 0; i < newMessages.size(); i++) {
            JSONObject message = newMessages.getJSONObject(i);
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageRole(message.getString("role"));
            chatMessage.setMessageContent(message.getString("content"));
            chatMessageMapper.insertChatMessage(chatMessage);
        }
    }
}
